package top.yueyazhui.word_freemarker.util;

import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class ExportDocUtil {

    /**
     * 由于 word 中图片是 base64 编码，因此需将图片转化为 base64 编码后的字符串
     * @return String
     */
    public String getImageBase64(String imgUrl) throws IOException {

        if (imgUrl == null || imgUrl == "") {
            return null;
        }

        URL url = new URL(imgUrl);
        // 下载资源，创建图片的输入流
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();

        // 分段读取
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        while((len = is.read(buffer)) != -1){
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] bytes = baos.toByteArray();

        // 关闭流
        baos.close();
        is.close();

        BASE64Encoder encoder = new BASE64Encoder();
        // 进行 base64 加密
        return encoder.encode(bytes);
    }
}
